/**
 * Created by WLG on 2018/11/12.
 */
const mongoose = require('mongoose');
const redisDB = require('../lib/redisManage');
let serverConfig = require('../config/serverConfig');
let CryptoUtil = require('../lib/cryptoUtil.js');
let Chat = mongoose.model('Chat');
/**
 * Chat服务
 */
class ChatService{
    static async load(item){
        let result = await Chat.find(item).exec();
        if(result){
            result = result[0];
        }
        return result;
    }

    static async save(item){
        let tempItem = new Chat(item);
        return await tempItem.save();
    }

    static async getCache(id,refresh){
        let result = "{}";
        let key = this.createKey(id);
        let item = null;
        if(refresh){

        }else{
            item = await redisDB.get(key);
        }
        if(item){
            result = item;
        }else {
            result = await this.load({_id:id});
            if (result) {
                await this.setCache(key,result)
            }
        }
        return result;
    }
    static async setCache(key,item){
        await redisDB.set(key,item,serverConfig.socketCommonCacheTime)
    }

    static createKey(id){
        return 'Chat:' + id;
    }

    static getMemSha1ByMemArray(memArray){
        let result = "";
        if(memArray){
            result = CryptoUtil.createSha1(memArray.sort().join("-"));
        }
        return result;
    }
    static async loadByMemsSha1(memsSha1){
        let result = await Chat.find({'memsSha1':memsSha1}).exec();
        if(result){
            result = result[0];
        }
        return result;
    }
}

module.exports = ChatService;